<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2022-2099 李志刚（854378082@qq.com）
 * @Date: 2019-01-03 20:14:16
 * @Description: 权限菜单管理
 * @LastEditors: 李志刚
 * @LastEditTime: 2022-04-30 22:26:53
 * @FilePath: /CoinCMF/app/Http/Controllers/Console/Rbac/MenuController.php
 */

namespace App\Http\Controllers\Console\Rbac;

use App\Customize\Func;
use App\Exceptions\FireFlyException;
use App\Models\Rbac\Menu;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Http\Requests\DetailRequest;
use App\Http\Requests\SortRequest;
use App\Http\Requests\Ums\MenuRequest;
use App\Http\Requests\Ums\MenuUpdateRequest;

class MenuController extends Controller
{
    public function getSelect()
    {
        $menus = Menu::select('id', 'parent_id', 'name', 'sort', 'url')->orderBy('sort', 'asc')->get();
        $select = Func::toTreeSelect($menus->toArray());
        $result[] = ['id' => 0, 'parent_id' => 0, 'title' => "一级菜单", 'value' => 0, 'expand' => true, 'selected' => false, 'checked' => false];
        $result = array_merge($result, $select);
        return $this->resJson(200, '获取成功', $result);
    }
    public function getList(Request $request)
    {
        // 一级菜单
        $all = Menu::select('id', 'parent_id', 'name', 'url', 'icon', 'label')->where('display', '=', '1')->orderBy('sort', 'asc')->orderBy('id', 'asc')->get();
        $leftmenu = array();
        // 判断权限
        $left = $all->where('parent_id', 0)->all();
        // 取到用户信息
        $user = Func::verfiyToken($request->header('Authorization'),'c-token');
        // 判断权限
        if (!in_array(1, $user->allRole)) {
            foreach ($left as $k => $v) {
                if (in_array($v['label'], (array) $user->allPermission)) {
                    $leftmenu[$k] = $v;
                }
            }
        } else {
            $leftmenu = $left;
        }
        // 二级菜单
        foreach ($leftmenu as $k => $v) {
            // 取所有下级菜单
            $submenu = $all->where('parent_id', '=', $v['id'])->all();
            // 进行权限判断
            if (!in_array(1, $user->allRole)) {
                $childSubMenu = [];
                foreach ($submenu as $s => $v) {
                    if (in_array($v['label'], (array) $user->allPermission)) {
                        $childSubMenu[$s] = $v;
                    }
                }
                $leftmenu[$k]['submenu'] = $childSubMenu;
            } else {
                $leftmenu[$k]['submenu'] = $submenu;
            }
        }
        // return $this->resJson(200, '获取成功', $leftmenu);
        // 三级菜单
        foreach ($leftmenu as $k => $v) {
            $submenu = $v['submenu'];
            // 所有二级
            foreach ($submenu as $s => $sub) {
                // 取所有下级菜单
                $there = $all->where('parent_id', '=', $sub['id'])->all();
                // 进行权限判断
                if (!in_array(1, $user->allRole)) {
                    $thereSubMenu = [];
                    foreach ($there as $t => $v) {
                        if (in_array($v['label'], (array) $user->allPermission)) {
                            $thereSubMenu[$t] = $v;
                        }
                    }
                    $submenu[$s]['there'] = $thereSubMenu;
                } else {
                    $submenu[$s]['there'] = $there;
                }
            }
            $leftmenu[$k]['submenu'] = $submenu;
        }
        return $this->resJson(200, '获取成功', $leftmenu);
    }
    public function getTree()
    {
        // 所有菜单
        $all = Menu::select('id', 'parent_id', 'name', 'url', 'display', 'sort')->orderBy('sort', 'asc')->orderBy('id', 'asc')->get();
        $tree = $this->toTree($all, 0);
        return $this->resJson(200, '获取成功', $tree);
    }
    private function toTree($data, $pid)
    {
        $tree = [];
        if ($data->count() > 0) {
            foreach ($data as $v) {
                if ($v->parent_id == $pid) {
                    $v = ['menu_id' => $v->id, 'title' => $v->name, 'sort' => $v->sort, 'display' => $v->display, '_showChildren' => true];
                    $v['children'] = $this->toTree($data, $v['menu_id']);
                    $tree[] = $v;
                }
            }
        }
        return $tree;
    }
    public function postCreate(MenuRequest $request)
    {
        $data = $request->all();
        $insert = ['parent_id' => $data['parent_id'], 'name' => $data['name'], 'url' => $data['url'], 'label' => $data['label'], 'icon' => $data['icon'], 'display' => $data['display'], 'sort' => $data['sort']];
        Menu::create($insert);
        return $this->resJson(200, '成功');
    }
    public function postEdit(MenuUpdateRequest $request)
    {
        $data = $request->all();
        if ($data['detail_id'] == $data['parent_id']) {
            throw new FireFlyException(400, "父级不能是自己");
        }
        $detail_id = $request->input('detail_id');
        $update = ['parent_id' => $data['parent_id'], 'name' => $data['name'], 'url' => $data['url'], 'label' => $data['label'], 'icon' => $data['icon'], 'display' => $data['display'], 'sort' => $data['sort']];
        Menu::where('id', $detail_id)->update($update);
        return $this->resJson(200, '成功');
    }
    public function getDetail(DetailRequest $request)
    {
        $detail_id = $request->input('detail_id');
        $detail = Menu::findOrFail($detail_id);
        return $this->resJson(200, '成功', $detail);
    }
    public function postSort(SortRequest $request)
    {
        $detail_id = $request->input('detail_id');
        $sort = $request->input('sort');
        Menu::where('id', $detail_id)->update(['sort' => $sort]);
        return $this->resJson(200, '成功');
    }
    public function postRemove(DetailRequest $request)
    {
        $detail_id = $request->input('detail_id');
        $arr = DB::select("SELECT t2.id as id FROM (SELECT @r AS _ids, (SELECT @r := GROUP_CONCAT(id) FROM ums_menu WHERE FIND_IN_SET(parent_id,@r)) AS id FROM (SELECT @r := " . $detail_id . ") vars NATURAL JOIN ums_menu h WHERE @r IS NOT NULL) t1,ums_menu t2 WHERE FIND_IN_SET(t2.id,t1._ids)");
        $ids = array_map(function ($q) {
            return $q->id;
        }, $arr);
        Menu::whereIn('id', $ids)->delete();
        return $this->resJson(200, '成功');
    }
}
